package com.mininglamp.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.mininglamp.model.Orders;


public class ExcelOperations {

	/**
	 * 读取excel
	 * @param inputStream
	 * @return
	 */
	public static List<String[]> readExcelFile(InputStream inputStream){
		
		try {
			Workbook wb = WorkbookFactory.create(inputStream);
			
			Sheet sheet = wb.getSheetAt(0);
			List<String[]> datas = new ArrayList<String[]>();
			for(Row row:sheet){
				if(row.getRowNum()!=0){
					int cells = row.getPhysicalNumberOfCells();
					String[] data = new String[cells];
					for(int j=0;j<cells;j++){
						Cell cell = row.getCell(j);
						cell.setCellType(CellType.STRING);
						if(cell!=null)
	                    {
							data[j] = cell.getStringCellValue();
	                    }
	                  }
					datas.add(data);
				}
			}
			return datas;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 写入excel
	 * @param template
	 * @param list
	 * @return
	 * @throws IOException 
	 * @throws InvalidFormatException 
	 * @throws EncryptedDocumentException 
	 */
	public static Workbook writeOrdersExcel(String template,List<Orders> list) throws Exception{
		
		Workbook wb = WorkbookFactory.create(new File(template));
		Sheet sheet = wb.getSheetAt(0);
		int rowNum = 1;
		String[] s1={"wetchatId","phone","receiptName","specification","address","courierId"};
		
		for(Orders order:list){
			int index = 0;
			Row row = sheet.createRow(rowNum);
			for(String ss:s1){
				Object value = PropertyUtils.getProperty(order, ss);
				row.createCell(index).setCellValue(value==null ? "":value.toString());
				index++;
			}
			rowNum++;
		}
		return wb;
		
	}
}
